package com.cincc.cincc_pbx.common;

import android.util.Base64;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AesUtils {

    static {
        Field field = null;
        try {
            field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
            field.setAccessible(true);
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
            field.set(null, Boolean.FALSE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * AES算法128位加密
     *
     * @param cleartext 加密字符串
     * @param aesKey    秘钥
     * @return
     */
    public static String encrypt(String cleartext, String aesKey) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec skeySpec = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(cleartext.getBytes(StandardCharsets.UTF_8));

//            return Base64.getEncoder().encodeToString(encrypted);
            return Base64.encodeToString(encrypted, Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES算法128位解密
     *
     * @param encrypMsg 解密字符串
     * @param aesKey    秘钥
     * @return
     */
    public static String decrypt(String encrypMsg, String aesKey) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(aesKey.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decbbdt = cipher.doFinal(Base64.decode(encrypMsg, Base64.DEFAULT));
            return new String(decbbdt, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
